package m.fun.service;

import m.appserver.AuthInfoUtil;
import m.base.model.UserInfo;
import m.common.model.util.*;
import m.common.service.Service;
import m.fun.model.BeginDetail;
import m.fun.model.BeginInfo;
import m.fun.model.BuildOrderModel;
import m.store.model.GoodsStockRecord;
import m.store.model.OrderModel;
import m.store.model.StockInfo;
import m.store.model.StoreGoods;
import m.store.service.StockInfoService;
import m.store.service.StoreNumberService;
import m.system.db.TransactionManager;
import m.system.exception.MException;
import m.system.util.GenerateID;
import m.system.util.NumberUtil;
import m.system.util.ObjectUtil;

import java.util.*;

public class BeginInfoService extends Service {
    public String save(BeginInfo model, List<BeginDetail> detailList) throws Exception {
        if(null==detailList||detailList.isEmpty()) throw new MException(this.getClass(),"请添加期初商品明细");
        ModelQueryCheck.init(model)
            .checkNotNull("guest.oid","请选择客户")
            .checkNotNull("status","状态错误")
            .checkStrEq("status", OrderModel.Status_Register,"登记状态才能修改")
            .doCheck(false,true);
        String msg="";
        if(ObjectUtil.isEmptyOid(model)){
            model.setOid(GenerateID.generatePrimaryKey());
            ModelUpdateUtil.insertModel(model);
            msg="保存成功";
        }else{
            ModelUpdateUtil.updateModel(model,"guest.oid","beginDate","remark");
            msg="修改成功";
        }
        ModelUpdateUtil.delete(BeginDetail.class, QueryCondition.eq("begin.oid",model.getOid()));
        Set<String> inNumMap=new HashSet<>();
        for(BeginDetail record : detailList){
            ModelQueryCheck.init(record)
                .checkNotNull("repository.oid","请选择期初仓库信息")
                .checkNotNull("goods.oid","请选择期初商品信息")
                .checkNotNull("price","请输入期初单价")
                .checkNumberRange("price",0D,999999999D,"期初单价不能小于0")
                .checkNotNull("num","请输入期初数量")
                .checkNumberRange("num",1D,999999999D,"期初数量不能小于1")
                .checkNotNull("preferential","请输入期初优惠金额")
                .doCheck(false,true);
            String goodsOid=record.getGoods().getOid();
            StoreGoods goods=ModelQueryList.getModel(record.getGoods());
            if(inNumMap.contains(goodsOid)) throw new MException(this.getClass(),goods.getName()+" 重复添加了");
            inNumMap.add(record.getGoods().getOid());
            record.setOid(GenerateID.generatePrimaryKey());
            record.setBegin(model);
            record.setOperDate(new Date());
            record.setAmount(NumberUtil.round(record.getNum()*record.getPrice()-record.getPreferential(),2));
            record.setPreferentialPrice(NumberUtil.round((record.getNum()*record.getPrice()-record.getPreferential())/record.getNum(),2));
        }
        ModelUpdateUtil.insertModels(detailList.toArray(new BeginDetail[0]));
        updateAmount(model.getOid());
        return msg;
    }
    private void updateAmount(String oid) throws MException {
        ModelUpdate.init(BeginInfo.class)
            .set("beginAmount",BeginDetail.class,"ifnull(sum(#{amount}),0)",QueryCondition.eq("begin.oid",oid))
            .execute(oid);
    }
    public void saveStockAndSale(String oid,String userOid) throws Exception {
        BeginInfo model=ModelQueryList.getModel(BeginInfo.class,oid,"*");
        if(!model.getInputUser().getOid().equals(userOid)) throw AuthInfoUtil.noPowerException;
        TransactionManager tm=new TransactionManager();
        try {
            tm.begin();
            //生成期初入库
            if(ObjectUtil.isEmptyOid(model.getStock())) {
                List<BeginDetail> recordList=ModelQueryList.getModelList(BeginDetail.class,
                    new String[]{"*"}, null,
                    QueryCondition.eq("begin.oid", model.getOid())
                );
                StockInfo stock = new StockInfo();
                stock.setOrderNo(StoreNumberService.getNextStockNumber(model.getStore().getOid()));
                stock.setStore(model.getStore());
                stock.setStatus(OrderModel.Status_Register);
                stock.setType(StockInfo.Type_Begin);
                stock.setInputDate(model.getInputDate());
                stock.setInputUser(model.getInputUser());
                stock.setStockDate(model.getBeginDate());
                stock.setGuest(model.getGuest());
                stock.setRemark(model.getRemark());
                List<GoodsStockRecord> stockRecords = new ArrayList<>();
                for(BeginDetail item : recordList){
                    GoodsStockRecord record = new GoodsStockRecord();
                    record.setRepository(item.getRepository());
                    record.setGoods(item.getGoods());
                    record.setStockNum(item.getNum());
                    record.setPrice(item.getPrice());
                    record.setPreferential(item.getPreferential());
                    record.setRemark(item.getRemark());
                    stockRecords.add(record);
                }
                getService(StockInfoService.class).saveAndSubmit(stock, stockRecords,false);
                getService(StockInfoService.class).check(stock.getOid(), stock.getStockDate(), stock.getRemark(), stock.getStore(), model.getCheckUser());
                model.setStock(stock);
                ModelUpdateUtil.updateModel(model, "stock.oid");
            }
            tm.commit();
        }catch (Exception e){
            tm.rollback();
            throw new MException(this.getClass(),"生成期初入库失败:"+e.getMessage());
        }
        model.setStatus(OrderModel.Status_Done);
        model.setBuildStatus(BuildOrderModel.Build_Done);
        ModelUpdateUtil.updateModel(model,"status","buildStatus");
    }

}
